﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using ChairtyBank.DAL;

namespace ChairtyBank
{
     partial class AddInstalmentForm : Form
    {
        public AddInstalmentForm()
        {
            InitializeComponent();
        }
        private Int32 InstId = 0;
        private Int32 loanId = 0;
        private Int32 userId = -1;
       // private Int32 rest ;
        private void AddInstalmentForm_Load(object sender, EventArgs e)
        {
            if (User.GetUser(userId).UType == "مدير عام")
            {
                btnDelete.Visible = true;
            }
            else 
            {
                btnDelete.Visible = false;
            }

        }
        public AddInstalmentForm(Int32 insId,Int32 Rest, Int32 userId) 
        {
            InitializeComponent();
            this.userId = userId;
            this.Text = User.GetUser(userId).UName;
            this.InstId = insId;
            InstalmentEntity IE = Instalment.GetInstalmentByInsId(insId);
            loanId = IE.Loan_ID;
            if (DateTime.Now > IE.DueDate)
                txtPenalty.Text = "0";
            else
                txtPenalty.Text = "0";
           
            txtInstalmentValue.Text = IE.Amount.ToString();
            txtTotal.Text=""+((Int32.Parse(txtPenalty.Text))+(Int32.Parse(txtInstalmentValue.Text)));
            DuetDatepkr.Value = DateTime.Parse(IE.DueDate.ToString());
            PayDatepkr.Value = DateTime.Parse(DateTime.Now.ToString());
            txtRest.Text = Rest.ToString();
            btnDelete.Enabled = false;
        }
        InstalmentEntity originalIE;
        public AddInstalmentForm(Int32 instId,Int32 Rest,Int32 userId,Boolean Payed) {
            InitializeComponent();
            this.userId = userId;
            this.Text = User.GetUser(userId).UName;
            this.InstId = instId;
            originalIE = Instalment.GetInstalmentByInsId(instId);
            loanId = originalIE.Loan_ID;
            if (originalIE.Penalty > 0)
                txtPenalty.Text = originalIE.Penalty.ToString();
            else
                txtPenalty.Text = "0";
            txtPAyed.Text = originalIE.Payed_Amount.ToString();
            txtTotal.Text = originalIE.Total.ToString();
            txtInstalmentValue.Text = originalIE.Amount.ToString();
            DuetDatepkr.Value = DateTime.Parse(originalIE.DueDate.ToString());
            PayDatepkr.Value = originalIE.DateOfPay;
            txtRest.Text = Rest.ToString();
            txtNotes.Text = originalIE.Notes;
            showTicket(instId);
            this.button2.Enabled=false;
            this.crystalReportViewer1.Enabled = true;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("هل تريد حذف القسط ؟", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (result == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    if(Loan.DeletePayed(originalIE.Loan_ID,originalIE.Penalty,originalIE.Payed_Amount))
                    {
                        originalIE.Rest+=originalIE.Payed_Amount;
                        originalIE.Notes=" ";
                        originalIE.payed=false;
                        originalIE.Payed_Amount=0;
                        originalIE.Penalty=0;
                        originalIE.DateOfPay=DateTime.Parse("01/01/2001 12:00:00 ص");
                        originalIE.Amount = Loan.GetLoanById(originalIE.Loan_ID).Instalment_amount;
                        
                    if( Instalment.Update(originalIE))
                    {
                      MessageBox.Show("تم الحذف بنجاح");
                    }
                        this.Close();
                    }
                }
                catch (Exception ecc)
                {
                    MessageBox.Show("لم يتم الحذف بشكل صحيح " + "\n" + ecc.Message);
                }

            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            DialogResult result;

            result = MessageBox.Show("هل تريد حفظ هذا البيان ؟", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (result == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    InstalmentEntity IE = getEntityDataFromForm();
                    if (IE.Rest == 0)
                    {
                        result = MessageBox.Show("سيتم تسديد كافة الأقساط. موافق؟", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (result == System.Windows.Forms.DialogResult.Yes)
                            FinishThisLoan(IE);
                    }
                    Instalment.Update(IE);
                    Loan.Update(IE);
                    if (IE.Notes == "سدد قبل 2010")
                    {
                        setPrevIns(IE);
                    }

                    showTicket(IE.Id);
                    button2.Enabled = false;
                    txtRest.Text = IE.Rest.ToString();
                }
                catch (Exception ecc)
                {
                    MessageBox.Show("يجب ادخال كل البيانات بشكل صحيح "+"\n"+ecc.Message);
                }

            }
        }

        private void FinishThisLoan(InstalmentEntity IE) {

            List<InstalmentEntity> IList = Instalment.GetInstalment(IE.Loan_ID);
            foreach (InstalmentEntity I in IList) {
                if (I.payed == false)
                {
                    I.Notes =IE.Notes;
                    I.payed = true;
                    I.Rest = 0;
                    I.userId = userId;
                    I.DateOfPay = IE.DateOfPay;
                    Instalment.Update(I);
                }
            }
            LoanEntity loan = Loan.GetLoanById(IE.Loan_ID);
            loan.EndDate = IE.DateOfPay;
            Loan.Update(loan);
        }
       
  

         private void setPrevIns(InstalmentEntity IE){

             List<InstalmentEntity> IList = Instalment.GetInstalment(IE.Loan_ID);
             foreach (InstalmentEntity I in IList)
             {
                 if (I.Id <IE.Id && I.payed==false)
                 {
                     I.Notes = IE.Notes;
                     I.payed = true;
                     I.Rest = IE.Rest;
                     I.DateOfPay = IE.DateOfPay;
                     Instalment.Update(I);
                 }
             }
         
         }
         
         
         
         private void showTicket(int insId) {
            this.testReport1.SetDataSource(charity_BankDataSet1);
            ticketQueryTableAdapter1.Fill(charity_BankDataSet1.TicketQuery,insId);
           // this.testReport1.SetParameterValue("Ins_Id", insId);
            crystalReportViewer1.ReportSource = this.testReport1;
            //this.crystalReportViewer1.Refresh();

        }
        private InstalmentEntity getEntityDataFromForm() {
            InstalmentEntity IE = new InstalmentEntity();
            IE.Id = InstId;
                IE.Loan_ID = loanId;
                if (txtNotes.Text == "")
                {
                    txtNotes.Text = " ";
                }
                IE.Notes = txtNotes.Text;
                IE.payed = bool.Parse("true");
                if (txtPAyed.Text == "" || txtTotal.Text == "" || txtNotes.Text == "") { }
                IE.Payed_Amount = Int32.Parse(txtPAyed.Text);
                IE.Penalty = Int32.Parse(txtPenalty.Text);
                IE.Total = Int32.Parse(txtTotal.Text);
                IE.DueDate = DuetDatepkr.Value.Date;
                IE.DateOfPay = PayDatepkr.Value;
                IE.Amount = Int32.Parse(txtInstalmentValue.Text);
                IE.Rest = Int32.Parse(txtRest.Text) - Int32.Parse(txtPAyed.Text);
                IE.userId = userId;
   
            return IE;
            
        }

        private void AddInstalmentForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            ((InstalmentForm)this.Owner).refreshForm();
        }


       

       
 
    }
}
